package com.jin.webvideo.externalInterfaces.video;

import com.jin.webvideo.base.util.CollectionsUtil;
import com.jin.webvideo.exception.UnavailableServiceException;
import com.jin.webvideo.externalInterfaces.entity.Filmography;
import com.jin.webvideo.externalInterfaces.entity.FilmographyInfo;
import com.jin.webvideo.service.ApiService;
import com.jin.webvideo.util.base.StringUtil;
import com.jin.webvideo.util.cloneUtil.CloneUtil;
import com.jin.webvideo.util.entity.VideoInfoBuilder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractVideoAPI implements VideoAPI, InitializingBean {
    @Autowired
    protected ApiService apiService;

    abstract String platformName();
    @Override
    public void afterPropertiesSet() throws Exception {
        apiService.registeVideoApi(platformName(), this);
    }

    public FilmographyInfo getActive(Filmography filmography, List<FilmographyInfo> infos, String tvid) throws UnavailableServiceException {
        return CollectionsUtil.first(infos, (info) -> tvid.equals(info.getId()));
    }

    @Override
    public Filmography setActive(final Filmography filmography, final String tvid) throws UnavailableServiceException {
        Filmography filmographys = CloneUtil.clone(filmography);
        List<FilmographyInfo> infos = filmographys.getVideoInfos();
        FilmographyInfo info = getActive(filmography, infos, tvid);
        // 没有VideoInfos，则补充为1
        if (CollectionsUtil.isEmpty(infos)){
            infos = new ArrayList<>();
            VideoInfoBuilder builder = new VideoInfoBuilder();
            // tvid为空时，取docid
            builder.setId(StringUtil.getDefault(tvid, filmography.getId()))
                    .setPlatform(filmography.getPlatform())
                    .setUrl(filmography.getUrl()).setTitle(filmography.getName())
                    .setDesc(filmography.getDesc())
                    .setNumber(1);
            info = builder.build();
            infos.add(info);
        }
        if (info == null){
            return filmographys;
        }
        if (StringUtil.isEmpty(filmography.getUrl())){
            filmographys.setUrl(info.getUrl());
        }
        filmographys.setVideoInfos(infos);
        filmographys.setAttrs(Filmography.ACTIVE_KEY, String.valueOf(info.getNumber()));
        filmographys.setAttrs(Filmography.COUNT_KEY, String.valueOf(infos.size()));
        return filmographys;
    }

    @Override
    public Filmography baseInfoWithVideoInfoList(String docid, String tvid, Integer pageNo, Integer pageSize) throws UnavailableServiceException {
        Filmography filmography = baseInfo(docid, tvid);
        List<FilmographyInfo> filmographyInfos = videoInfoList(docid, tvid, pageNo, pageSize);
        filmography.setVideoInfos(filmographyInfos);
        return filmography;
    }
}
